// pages/search/bluetooth.js
Page({
  /**
   * 组件的初始数据
   */
  data: {
    btDevices: [], //搜索到的蓝牙设备列表
    isBluetoothSearching: false, //蓝牙是否正在搜索
    isBTInit: false, //蓝牙适配器是否初始化
  },
  onReady() {
    const that = this;
    that.initBT();
    wx.onBluetoothAdapterStateChange((result) => {
      this.initBT();
    });
    wx.onBluetoothDeviceFound(function (params) {
      var list = that.data.btDevices;
      var devices = params.devices;
      devices.forEach(element => {
        list.push(element);
      });
      that.setData({
        btDevices: list
      });
      //console.log('发现新设备')
      //console.log(devices)
      //console.log(that.ab2hex(devices[0].advertisData))
    });
  },
  onBluetoothClick(e) {
    var data = Object.assign({}, getApp().globalData);
    data.mac = this.data.btDevices[e.currentTarget.id].deviceId;
    //console.log(data.mac);
    this.saveSettings(data, function () {
      wx.showToast({
        title: '蓝牙地址已保存',
      });
      getApp().readSettingsSync();
      //console.log(getApp())
    });
  },
  onSwitchChanged(e) {
    //console.log(e);
    if (e.detail.value) {
      this.initBT();
    } else {
      wx.closeBluetoothAdapter({
        success: (res) => {
          this.setData({
            isBTInit: false,
            isBluetoothSearching: false
          })
        },
      })
    }
  },
  initBT() {
    wx.openBluetoothAdapter({
      success: res => {
        //console.log(res)
        //console.log("蓝牙初始化成功！");
        this.setData({
          isBTInit: true,
        })
      },
      fail: error => {
        this.setData({
          isBTInit: false
        });
        wx.showToast({
          title: '当前蓝牙适配器不可用',
          icon: 'none'
        });
      },
    });
  },
  startSearch() {
    if (this.data.isBTInit) {
      this.startDevicesDiscovery();
    } else {
      wx.showToast({
        title: '请先开启蓝牙',
        icon: 'none'
      })
    }
  },
  //扫描蓝牙设备
  startDevicesDiscovery() {
    let that = this;
    //console.log("开始搜索蓝牙")
    wx.startBluetoothDevicesDiscovery({
      success: () => {
        //console.log("搜索蓝牙成功")
        that.setData({
          isBluetoothSearching: true,
          btDevices: []
        });
      },
      fail: error => {
        wx.showToast({
          title: '启动扫描失败' + JSON.stringify(error),
          icon: 'none'
        });
      },
    });
  },
  ab2hex(buffer) {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
    return hexArr.join('');
  },
  //停止扫描
  stopDevicesDiscovery() {
    let that = this;
    wx.stopBluetoothDevicesDiscovery({
      success: res => {
        that.setData({
          isBluetoothSearching: false
        });
      },
      complete: res => {
        //console.log(res)
      }
    });
  },
  saveSettings(data, callback) {
    //console.log("保存设置")
    //console.log(data)
    wx.setStorage({
      key: 'settings',
      data: data,
      success: callback,
      fail: () => {
        wx.showToast({
          title: '保存失败',
          icon: 'none'
        });
      }
    });
  },
})